package com.yellowpage.white.util;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class DomParser {
    private Document doc;

    public DomParser(String filePath) {
        parsing(filePath);
    }

    public DomParser(File file) {
        parsing(file);
    }

    public DomParser(InputStream input) {
        parsing(input);
    }


    private void parsing(String filePath){
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.parse(new File(filePath));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parsing(File file){
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.parse(file);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parsing(InputStream input){
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.parse(input);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }



    public Document getDocument(){
        return this.doc;
    }
    
    public static Node getSubNodeByName(Node node, String name){
    	NodeList subNodes = node.getChildNodes();
		for (int n = 0; n < subNodes.getLength(); n++) {
			
			Node subNode = (Node) subNodes.item(n);
			
			if (subNode.getNodeType() == Node.ELEMENT_NODE
					&& subNode.getNodeName().equals(name)) {
				return subNode;
			}
		}	
		return null;
    }
    
    public static List getSubNodeListByName(Node node, String name){
    	List nodelist = new ArrayList();
    	
    	NodeList subNodes = node.getChildNodes();
		for (int n = 0; n < subNodes.getLength(); n++) {
			
			Node subNode = (Node) subNodes.item(n);

			if (subNode.getNodeType() == Node.ELEMENT_NODE
					&& subNode.getNodeName().equals(name)) {
				nodelist.add(subNode);
			}
		}	
		return nodelist;
    }

}
